package GameMain.View.Login
{
	import Engine.Module.ViewBase;
	
	import GameMain.Game;
	import GameMain.Macro.MacroEvent;
	
	import Interface.UIControl.ITextBase;
	
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.ui.Keyboard;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	import library.SocketData.SocketData;
	
	public class Login extends ViewBase
	{
		
		private var _inputTxt:ITextBase;
		private var _ipTxt:ITextBase;
		private var _portTxt:ITextBase;
		private var _userName:String = "";
		private var _proTxt:ITextBase;
		private var _pingTimer:Timer = new Timer(1000);
		
		
		public function Login(p_content:Sprite=null)
		{
			super(p_content);
			this._inputTxt =  Game.ControlMgr.getText(this._content["USER_NAME"]);
			this._inputTxt.setInputText(true);
			this._inputTxt.textField.restrict = "0-9a-z";
			
			this._proTxt = Game.ControlMgr.getText(this._content["USER_PRO"]);
			this._proTxt.setInputText(true);
			this._proTxt.textField.restrict = "1-5";
			
			this._ipTxt = Game.ControlMgr.getText(this._content["IP_TXT"]);
			this._ipTxt.setInputText(true);
			this._ipTxt.textField.restrict = "0-9.";
			this._ipTxt.text = "172.16.0.143"
			
			this._portTxt = Game.ControlMgr.getText(this._content["PORT_TXT"]);
			this._portTxt.setInputText(true);
			this._portTxt.textField.restrict = "0-9";
			this._portTxt.text = "7019";
			
			
			this._pingTimer.addEventListener(TimerEvent.TIMER,onPingStart);
			
			Game.ControlMgr.getButton(this._content["DENG_LU"]).setOnClickFun(onLogin);
			Game.EngineMgr.setConnectFun(onConnect);
			Game.EngineMgr.registerEvent(MacroEvent.MSG_TO_SERVER_PING,onPingBack);
		}
		
		private function onLogin():void
		{
			this._userName = this._inputTxt.text;
			if(_userName == "")
				return;
			var ip:String = this._ipTxt.text;
			var port:int = int(this._portTxt.text);
			Game.EngineMgr.connectSocket(ip,port);
		}
		
		private function onConnect():void
		{
			this._pingTimer.start();
		}
		
		private function onPingStart(e:TimerEvent):void
		{
			var data:SocketData = new SocketData();
			data.writeUInt32(getTimer());
			this.sendMsg(MacroEvent.MSG_TO_SERVER_PING,data);
		}
		
		private function onPingBack(data:SocketData):void
		{
			var nowTime:int = getTimer();
			var preTime:int = data.readUInt32();
			var ping:int = (nowTime - preTime)/2
			Game.EngineMgr.printLog("The Server Ping is:"+String(ping));
		}
		
		
		override protected function onShowBack():void
		{
			Game.EngineMgr.regestKeyUpEvent(Keyboard.ENTER,onLogin);
		}
		
		override protected function onDisposeBack():void
		{
			Game.EngineMgr.destroyKeyUpEvent(Keyboard.ENTER);
		}
	}
}